const express = require('express');
const dayjs = require('dayjs');
const router = express.Router();
const model = require('../../db/cloudControl/anchorMod');

// 分页查询
router.get('/page-list', async (req, res) => {
	try {
		const { page = 1, limit = 1000, display_id, anchor_id, coins, followers, following, audience, region, country, source, tags, is_connected, is_joined, verification_result, agent } = req.query;

		// 构建查询条件
		const conditions = {};

		console.log('req.session.userLevel', req.session.userLevel);

		// 如果是管理员级别，可以查看自己名下所有主播
		if (req.session.userLevel === 1) {
			conditions.admin = req.session.userId;
		}

		// 如果是经纪人级别，只能查看自己的主播
		if (req.session.userLevel === 2) {
			conditions.agent = req.session.userId;
		}

		// 字符串模糊查询
		if (display_id) conditions.display_id = { $regex: display_id };
		if (anchor_id) conditions.anchor_id = { $regex: anchor_id };
		if (region) conditions.region = { $regex: region };
		if (country) conditions.country = { $regex: country };
		if (tags) conditions.tags = { $regex: tags };
		if (source) conditions.source = { $regex: source };
		if (verification_result) conditions.verification_result = { $regex: verification_result };

		// 数值类型比较（大于等于）
		const numericConditions = [];
		if (coins) {
			numericConditions.push({
				$gte: [{ $toInt: '$coins' }, parseInt(coins)],
			});
		}
		if (followers) {
			numericConditions.push({
				$gte: [{ $toInt: '$followers' }, parseInt(followers)],
			});
		}
		if (following) {
			numericConditions.push({
				$gte: [{ $toInt: '$following' }, parseInt(following)],
			});
		}
		if (audience) {
			numericConditions.push({
				$gte: [{ $toInt: '$audience' }, parseInt(audience)],
			});
		}

		// 如果有数值条件，添加到查询条件中
		if (numericConditions.length > 0) {
			conditions.$expr = { $and: numericConditions };
		}

		// 布尔值查询
		if (is_connected !== undefined) conditions.is_connected = is_connected === 'true';
		if (is_joined !== undefined) conditions.is_joined = is_joined === 'true';

		if (agent == 'true') {
			conditions.agent = { $exists: true }; // 查询 agent 为空的记录
		} else if (agent == 'false') {
			conditions.agent = { $exists: false }; // 查询 agent 有值的记录
		}

		// 计算总数
		const total = await model.countDocuments(conditions);

		// 查询数据
		const list = await model
			.find(conditions)
			.populate('agent', 'userName') // 关联查询经纪人信息
			.lean()
			.skip((page - 1) * limit)
			.limit(Number(limit))
			.sort({ created_at: -1 });

		res.json({
			code: 0,
			data: {
				list,
				total,
				page: Number(page),
				limit: Number(limit),
			},
			msg: '查询成功',
		});
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message,
		});
	}
});

// 更新
router.post('/update', async (req, res) => {
	try {
		const { _id, ...updateData } = req.body;

		if (!_id) {
			return res.json({
				code: -1,
				msg: '缺少_id参数',
			});
		}

		// 如果是经纪人，验证是否为其管理的主播
		if (req.session.level === 1) {
			const anchor = await model.findById(_id);
			if (!anchor || anchor.agent.toString() !== req.session.userId) {
				return res.json({
					code: -1,
					msg: '无权操作此主播数据',
				});
			}
		}

		updateData.updated_at = dayjs().format('YYYY-MM-DD HH:mm:ss');

		const result = await model.findByIdAndUpdate(_id, updateData, { new: true }).populate('agent', 'username');

		if (!result) {
			return res.json({
				code: -1,
				msg: '未找到要更新的数据',
			});
		}

		res.json({
			code: 0,
			data: result,
			msg: '更新成功',
		});
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message,
		});
	}
});

// 删除
router.post('/delete', async (req, res) => {
	try {
		const { ids } = req.body;

		const result = await model.deleteMany({ _id: { $in: ids } });

		res.json({
			code: 0,
			msg: '删除成功',
		});
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message,
		});
	}
});

module.exports = router;
